// 股票交易分析系统 - 前端JavaScript

// 全局变量
let refreshInterval;
let charts = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeDashboard();
    setupEventListeners();
    startAutoRefresh();
});

// 初始化仪表板
function initializeDashboard() {
    console.log('仪表板初始化中...');
    
    // 添加加载动画
    showLoadingState();
    
    // 检查系统状态
    checkSystemHealth();
    
    // 隐藏加载动画
    setTimeout(() => {
        hideLoadingState();
    }, 1000);
}

// 设置事件监听器
function setupEventListeners() {
    // 窗口大小改变时重新调整图表
    window.addEventListener('resize', function() {
        Object.values(charts).forEach(chart => {
            if (chart && typeof chart.resize === 'function') {
                chart.resize();
            }
        });
    });
    
    // 页面可见性改变时的处理
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            stopAutoRefresh();
        } else {
            startAutoRefresh();
        }
    });
}

// 开始自动刷新
function startAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    refreshInterval = setInterval(() => {
        refreshDashboardData();
    }, 30000); // 30秒刷新一次
    
    console.log('自动刷新已启动');
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
        console.log('自动刷新已停止');
    }
}

// 刷新仪表板数据
async function refreshDashboardData() {
    try {
        console.log('刷新数据中...');
        
        // 显示刷新指示器
        showRefreshIndicator();
        
        // 并行获取所有数据
        const [summaryData, holdingsData, tradesData] = await Promise.all([
            fetchPerformanceSummary(),
            fetchCurrentHoldings(),
            fetchRecentTrades()
        ]);
        
        // 更新UI
        updateSummaryCards(summaryData);
        updateHoldingsTable(holdingsData);
        updateRecentTrades(tradesData);
        
        // 更新时间戳
        updateTimestamp();
        
        // 隐藏刷新指示器
        hideRefreshIndicator();
        
        console.log('数据刷新完成');
        
    } catch (error) {
        console.error('刷新数据失败:', error);
        showErrorMessage('数据刷新失败，请检查网络连接');
        hideRefreshIndicator();
    }
}

// 获取性能汇总数据
async function fetchPerformanceSummary() {
    const response = await fetch('/api/performance');
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
}

// 获取当前持仓数据
async function fetchCurrentHoldings() {
    const response = await fetch('/api/current-holdings');
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
}

// 获取最近交易数据
async function fetchRecentTrades() {
    const response = await fetch('/api/recent-trades?limit=10');
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
}

// 更新汇总卡片
function updateSummaryCards(data) {
    const elements = {
        'total-trades': data.total_trades,
        'win-rate': data.win_rate.toFixed(1) + '%',
        'avg-return': data.avg_return.toFixed(2) + '%',
        'net-return': data.net_return.toFixed(2) + '%'
    };
    
    Object.entries(elements).forEach(([id, value]) => {
        const element = document.getElementById(id);
        if (element) {
            // 添加动画效果
            element.style.transform = 'scale(1.1)';
            element.textContent = value;
            
            setTimeout(() => {
                element.style.transform = 'scale(1)';
            }, 200);
        }
    });
}

// 更新持仓表格
function updateHoldingsTable(holdings) {
    const tbody = document.getElementById('holdings-table');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    if (holdings.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4 text-muted">
                    <i class="fas fa-inbox fa-2x mb-2"></i><br>
                    暂无持仓数据
                </td>
            </tr>
        `;
        return;
    }
    
    holdings.forEach(holding => {
        const row = document.createElement('tr');
        row.className = 'fade-in';
        row.innerHTML = `
            <td><strong>${holding.code}</strong></td>
            <td>¥${holding.buy_price.toFixed(2)}</td>
            <td>¥${holding.current_price.toFixed(2)}</td>
            <td>
                <span class="badge ${holding.return_rate >= 0 ? 'bg-success' : 'bg-danger'}">
                    ${holding.return_rate.toFixed(2)}%
                </span>
            </td>
            <td>${holding.hold_days}天</td>
            <td class="text-muted small" title="${holding.reason}">${truncateText(holding.reason, 30)}</td>
        `;
        tbody.appendChild(row);
    });
}

// 更新最近交易
function updateRecentTrades(trades) {
    const container = document.getElementById('recent-trades');
    if (!container) return;
    
    container.innerHTML = '';
    
    if (trades.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-chart-line fa-2x mb-3"></i>
                <p>暂无交易记录</p>
            </div>
        `;
        return;
    }
    
    trades.forEach(trade => {
        const tradeElement = document.createElement('div');
        tradeElement.className = 'd-flex justify-content-between align-items-center mb-3 pb-2 border-bottom fade-in';
        tradeElement.innerHTML = `
            <div>
                <strong>${trade.code}</strong>
                <br>
                <small class="text-muted">${trade.buy_date}</small>
            </div>
            <div class="text-end">
                <span class="badge ${trade.return_rate >= 0 ? 'bg-success' : 'bg-danger'}">
                    ${trade.return_rate.toFixed(2)}%
                </span>
                <br>
                <small class="text-muted">${trade.status}</small>
            </div>
        `;
        container.appendChild(tradeElement);
    });
}

// 检查系统健康状态
async function checkSystemHealth() {
    try {
        const response = await fetch('/health');
        const health = await response.json();
        
        const indicator = document.querySelector('.status-indicator');
        if (indicator) {
            if (health.status === 'healthy') {
                indicator.className = 'status-indicator online';
                indicator.title = '系统正常运行';
            } else {
                indicator.className = 'status-indicator offline';
                indicator.title = '系统异常: ' + health.error;
            }
        }
    } catch (error) {
        console.error('健康检查失败:', error);
    }
}

// 显示加载状态
function showLoadingState() {
    const loadingElements = document.querySelectorAll('.loading-placeholder');
    loadingElements.forEach(element => {
        element.innerHTML = '<div class="loading"></div>';
    });
}

// 隐藏加载状态
function hideLoadingState() {
    const loadingElements = document.querySelectorAll('.loading');
    loadingElements.forEach(element => {
        element.remove();
    });
}

// 显示刷新指示器
function showRefreshIndicator() {
    const updateTime = document.getElementById('update-time');
    if (updateTime) {
        updateTime.innerHTML = '<div class="loading"></div>';
    }
}

// 隐藏刷新指示器
function hideRefreshIndicator() {
    // 在updateTimestamp中会自动隐藏
}

// 更新时间戳
function updateTimestamp() {
    const updateTime = document.getElementById('update-time');
    if (updateTime) {
        updateTime.textContent = new Date().toLocaleString('zh-CN');
    }
}

// 显示错误消息
function showErrorMessage(message) {
    // 创建错误提示
    const alert = document.createElement('div');
    alert.className = 'alert alert-danger alert-dismissible fade show position-fixed';
    alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alert.innerHTML = `
        <i class="fas fa-exclamation-triangle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alert);
    
    // 5秒后自动移除
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}

// 显示成功消息
function showSuccessMessage(message) {
    const alert = document.createElement('div');
    alert.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alert.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 3000);
}

// 截断文本
function truncateText(text, maxLength) {
    if (!text) return '';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

// 格式化数字
function formatNumber(num, decimals = 2) {
    if (num === null || num === undefined) return '-';
    return parseFloat(num).toFixed(decimals);
}

// 格式化百分比
function formatPercentage(num, decimals = 2) {
    if (num === null || num === undefined) return '-';
    return parseFloat(num).toFixed(decimals) + '%';
}

// 格式化货币
function formatCurrency(num, decimals = 2) {
    if (num === null || num === undefined) return '-';
    return '¥' + parseFloat(num).toFixed(decimals);
}

// 导出功能
function exportData(type) {
    switch (type) {
        case 'csv':
            exportToCSV();
            break;
        case 'excel':
            exportToExcel();
            break;
        case 'pdf':
            exportToPDF();
            break;
        default:
            console.warn('未知的导出类型:', type);
    }
}

// 导出为CSV
function exportToCSV() {
    // 实现CSV导出逻辑
    showSuccessMessage('CSV导出功能开发中...');
}

// 导出为Excel
function exportToExcel() {
    // 实现Excel导出逻辑
    showSuccessMessage('Excel导出功能开发中...');
}

// 导出为PDF
function exportToPDF() {
    // 实现PDF导出逻辑
    showSuccessMessage('PDF导出功能开发中...');
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函数：节流
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
    
    // 清理图表
    Object.values(charts).forEach(chart => {
        if (chart && typeof chart.destroy === 'function') {
            chart.destroy();
        }
    });
});

// 全局错误处理
window.addEventListener('error', function(event) {
    console.error('全局错误:', event.error);
    showErrorMessage('系统发生错误，请刷新页面重试');
});

// 未处理的Promise拒绝
window.addEventListener('unhandledrejection', function(event) {
    console.error('未处理的Promise拒绝:', event.reason);
    showErrorMessage('网络请求失败，请检查连接');
});

console.log('仪表板JavaScript已加载完成');
